package com.dxp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dxp.common.R;
import com.dxp.dto.DishDto;
import com.dxp.pojo.*;
import com.dxp.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    SetmealDishService setmealDishService;
    @Autowired
    SetmealService setmealService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    RedisTemplate redisTemplate;

    //新增菜品
    @PostMapping
    public R<String> addDish(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        //清理某个分类下面的菜品缓存数据
        String key="dish_"+dishDto.getCategoryName()+"_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }
    //分页查询
    @GetMapping("/page")
    public R<Page> list(int page,int pageSize,String name){
        Page page1 = dishService.listDish(page, pageSize, name);
        return R.success(page1);
    }
    //修改菜品信息(通过id得到菜品信息)
    @GetMapping("/{id}")
    public R<DishDto> update(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdUpdateDish(id);
        return R.success(dishDto);
    }
    //修改
    @PutMapping
    public R<String> UpdateDish(@RequestBody DishDto dishDto){
        dishService.updateDish(dishDto);
        //清理某个分类下面的菜品缓存数据
        String key="dish_"+dishDto.getCategoryName()+"_1";
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }
    //添加套餐时根据分类展示菜品
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> list1=null;
        //先从redis中获取缓存数据
        //动态构造key
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        list1= (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (list1!= null)
        {
            //如果存在，直接返回，无需查询数据库
            return R.success(list1);
        }
        //如果不存在，查询数据库
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.eq("status",1);
        dishQueryWrapper.eq(dish.getCategoryId()!=null,"category_id",dish.getCategoryId());
        List<Dish> dishList = dishService.list(dishQueryWrapper);
        list1 = new ArrayList<DishDto>();
        for (Dish dishInfoRecord : dishList) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dishInfoRecord,dishDto);
            Long categoryId = dishInfoRecord.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            Long dishInfoRecordId = dishInfoRecord.getId();
            QueryWrapper<DishFlavor> dishFlavorQueryWrapper = new QueryWrapper<>();
            dishFlavorQueryWrapper.eq("dish_id",dishInfoRecordId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            list1.add(dishDto);
        }
        //如果不存在，查询数据库，并将数据加入缓存
        redisTemplate.opsForValue().set(key,list1,60, TimeUnit.MINUTES);
        return R.success(list1);
    }
    //删除菜品
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        dishService.deleteWithDish(ids);
        return R.success("删除菜品成功");
    }
    //批量起售
    @PostMapping("/status/1")
    public R<String> update(@RequestParam List<Long> ids){
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.in("id",ids);
        List<Dish> dishList = dishService.list(dishQueryWrapper);
        dishList.stream().map((item)->{
            item.setStatus(1);
            return item;
        }).collect(Collectors.toList());
        dishService.updateBatchById(dishList);
        return R.success("修改成功");
    }
    //批量停售
    @PostMapping("/status/0")
    public R<String> update1(@RequestParam List<Long> ids){
        //先把菜品停售
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.in("id",ids);
        List<Dish> dishList = dishService.list(dishQueryWrapper);
        dishList.stream().map((item)->{
            item.setStatus(0);
            return item;
        }).collect(Collectors.toList());
        dishService.updateBatchById(dishList);
        //再把对应到的套餐停售
        QueryWrapper<SetmealDish> setmealQueryWrapper = new QueryWrapper<>();
        setmealQueryWrapper.in("dish_id",ids);
        List<SetmealDish> setmealDishList = setmealDishService.list(setmealQueryWrapper);
        setmealDishList=setmealDishList.stream().map((item)->{
            Long setmealId = item.getSetmealId();
            Setmeal setmeal= setmealService.getById(setmealId);
            setmeal.setStatus(0);
            setmealService.updateById(setmeal);
            return item;
        }).collect(Collectors.toList());
        return R.success("修改成功");
    }
}
